/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 分刀与合刀 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];
try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
		units: 'mm'
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }


	var stepList = GEN.getStepList({job:job})
	// step过滤
    stepList = stepList.filter(function(step){
		var regexp = new RegExp(par.step,"ig")
		return regexp.test(step)
	})
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	var drill_layer = "drl"
	var tmp_drl = drill_layer + "_tmp"
	if(stepList.length == 0) { throw "未发现step:"+par.step_filter }
	stepList.forEach(function(step){
		GEN.openStep({job:job, name:step})
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  //单位初始化
        GEN.zoomHome();  //窗口显示回到原始位置
        // 显示finish size 
		if (GEN.isLayerExists({ job: job, layer: tmp_drl })) {
			GEN.deleteLayer({ job: job, layer: [tmp_drl] });
		}
		GEN.matrixAddLayer({ job: job, layer: tmp_drl, type: "drill" });
		GEN.workLayer({ name: drill_layer, display_number: 2, clear_before: 'yes' });
		GEN.selMoveOther({ target_layer: tmp_drl, invert: 'no', dx: 0, dy: 0, size: 0 });
		GEN.workLayer({ name: tmp_drl, display_number: 2, clear_before: 'yes' });
		GEN.selMoveOther({ target_layer: drill_layer, invert: 'no', dx: 0, dy: 0, size: 0 });
		GEN.workLayer({ name: drill_layer, display_number: 2, clear_before: 'yes' });
		GEN.deleteLayer({ job: job, layer: [tmp_drl] });
		// 1. 选中槽孔拷贝到 _slot
		if (GEN.isLayerExists({job:job, layer:drill_layer + "_slot"})){
            GEN.deleteLayer({job:job, layer:[drill_layer + "_slot"]});
        }
        GEN.createLayer({job:job,layer:drill_layer + "_slot",context:'misc',type:'drill'})
        GEN.selectByFilter({feat_types:"line"})
		GEN.selectByFilter({exclude_syms:"r*"})
        if(GEN.getSelectCount() > 0) {
            GEN.selMoveOther({target_layer:drill_layer + "_slot",invert:'no',dx:0,dy:0,size:0})
		    GEN.workLayer({name:drill_layer + "_slot",display_number:2,clear_before:'yes'})
			GEN.selMoveOther({target_layer:drill_layer,invert:'no',dx:0,dy:0,size:0})
            setTool({
                job:job, 
                step:step,
                layer:drill_layer,
                units: par.units,
                callback: function (toolinfo) {
                    for (var key in toolinfo) {
                        var info = toolinfo[key]
                        if(info.shape =="slot") {
							info.drill_size = foo(info.drill_size)
                        }
                    }
                }
			})
            GEN.deleteLayer({job:job, layer:[drill_layer + "_slot"]});
        } else {
            GEN.deleteLayer({job:job, layer:[drill_layer + "_slot"]});
		}

		var repeat_eq = drill_layer + "_eq";
		var repeat_neq = drill_layer + "_neq";
		[repeat_eq, repeat_neq].forEach(function(v){
			if(GEN.isLayerExists({job:job, layer:v})){GEN.deleteLayer({job:job, layer: [v]})}
			GEN.matrixAddLayer({job:job, layer:v, type:"drill"})
        })
        
        GEN.workLayer({name:drill_layer,display_number:2,clear_before:'yes'})
        GEN.selCopyOther({dest:'layer_name',target_layer:tmp_drl,invert:'no',dx:0,dy:0,size:0})
        GEN.workLayer({name:tmp_drl,display_number:2,clear_before:'yes'})
        GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=yes")
        GEN.units({type:"inch"})
        GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
        GEN.units({ type: par.units });
        GEN.selectByFilter({include_syms:"construct*"})
		GEN.selReverse()
        if (GEN.getSelectCount () > 0) {
            GEN.selDelete()
		}
		GEN.workLayer({name:drill_layer,display_number:2,clear_before:'yes'})
        GEN.selRefFeat({layers:tmp_drl,use:'filter',mode:'touch'})
		var feats = GEN.getFeatures({job:job,step:step,layer:drill_layer, units:par.units, options:"select"}) || [];
		feats.forEach(function(item) {
			if (item.type == "pad") {
				GEN.COM("sel_net_feat,operation=select,x="+item.x+",y="+item.y+",use_ffilter=no")
			} else if (item.type == "line"){
				GEN.COM("sel_net_feat,operation=select,x="+item.xs+",y="+item.ys+",use_ffilter=no")
			}
			if(GEN.getSelectCount() > 1) {
				// 判断等大不等大 重复孔
				var feats = GEN.getFeatures({job:job,step:step,layer:drill_layer, units:par.units, options:"select"})
				var eq = true;
				feats.reduce(function(a,b){
					if(a.symbol != b.symbol) {eq = false}
					return b
				})
				if(eq) {
					GEN.selMoveOther({target_layer:repeat_eq,invert:'no',dx:0,dy:0,size:0})
				} else {
					GEN.selMoveOther({target_layer:repeat_neq,invert:'no',dx:0,dy:0,size:0})
				}
			}
			GEN.selClearFeature()
		})
		
		var tmp_info = {};
		var tmparr = [repeat_eq, repeat_neq];
		tmparr.forEach(function(v, i){
			GEN.workLayer({name:v,display_number:2,clear_before:'yes'})
			GEN.selAllFeat()
			if(GEN.getSelectCount()> 0) {
				// 等大相交孔：0.45≤孔径≤2.0mm，以0.003作为后缀；
				// 不等大相交孔：0.4≤孔径≤6.0mm，以0.003作为后缀；
				setTool({
					job:job, 
					step:step,
					layer:v,
					units: par.units,
					callback: function (toolinfo) {
						for (var key in toolinfo) {
							var info = toolinfo[key];
							info.drill_size = Number(info.drill_size);
							if(i == 0) {
								if(450 <= info.drill_size && info.drill_size <= 2000) {
									info.drill_size = foo(info.drill_size)
								}
							} else {
								if(400 <= info.drill_size && info.drill_size <= 6000) {
									info.drill_size = foo(info.drill_size)
								}
							}
						}
					}
				})
				if(GEN.isLayerExists({job:job, layer: "org-" + drill_layer})){
					GEN.selClearFeature()
					var syms = GEN.getLayerSymsHist({job:job, step:step, layer:v, units:"mm"})
					for (var key in syms) {
						GEN.workLayer({name:v,display_number:2,clear_before:'yes'})
						GEN.selectByFilter({include_syms:key})
						if(GEN.isLayerExists({job:job, layer:v + "_tmp"})){GEN.deleteLayer({job:job, layer:v + "_tmp"})}
						GEN.selCopyOther({dest:'layer_name',target_layer:v + "_tmp",invert:'no',dx:0,dy:0,size:0})
						GEN.workLayer({name:"org-" + drill_layer,display_number:2,clear_before:'yes'})
						GEN.selRefFeat({layers: v + "_tmp",use:"filter",mode:"cover"})
						if(GEN.getSelectCount() > 0) {
							var finish_size = GEN.getFeatures({job:job,step:step,layer:"org-" + drill_layer,options:"select",units:"mm"}).map(function(v){return v.symbol.slice(1)})
							if(finish_size.length > 0 ) {
								tmp_info[key.slice(1)] = finish_size[0]
							}
						}
						if(GEN.isLayerExists({job:job, layer:v + "_tmp"})){GEN.deleteLayer({job:job, layer:v + "_tmp"})}
					}
				}

				GEN.workLayer({name:v,display_number:2,clear_before:'yes'})
				GEN.selMoveOther({target_layer:drill_layer,invert:'no',dx:0,dy:0,size:0})
            }
			GEN.deleteLayer({job:job, layer: [v]})
		})

		// 合刀
		GEN.COM("tools_show,layer="+drill_layer)
		GEN.COM("tools_merge_ex,layer="+drill_layer+",mode=merge_and_sort")


		setTool({
			job:job, 
			step:step,
			layer:drill_layer,
			units: par.units,
			callback: function (toolinfo) {
				for (var key in toolinfo) {
					var info = toolinfo[key]
					if(tmp_info[info.drill_size]){
						info.finish_size = tmp_info[info.drill_size]
					}
					if(info.drill_size == info.finish_size && info.finish_size[info.finish_size.length-1] == "3"){
						info.finish_size = Math.floor(info.finish_size/10) * 10
					}
				}
			}
		})

		if(GEN.isLayerExists({job:job, layer:tmp_drl})){GEN.deleteLayer({job:job, layer:[tmp_drl]})}
		if(GEN.isLayerExists({job:job, layer:tmp_drl +"+++"})){GEN.deleteLayer({job:job, layer:[tmp_drl+"+++"]})}

	})




	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}


function setTool(props) {
	var units = props.units;
	GEN.units({type:"mm"})
	var job = props.job;
	var step = props.step;
	var layer = props.layer;
	var tool_info = GEN.getTool({job:job, step: step , layer:layer, units:"mm"});

	// 操作tool_info
	props.callback(tool_info)

	GEN.COM("tools_show,layer="+layer)
	GEN.COM("tools_tab_reset")
	var typehash = {
		non_plated:"nplate",
		plated:"plate",
		via:"via",
		laser:"via"
	}
	Object.keys(tool_info).forEach(function(key){
		var item = tool_info[key]
		if (item.shape == "hole") {
			GEN.COM("tools_tab_add,num="+key
			+",shape="+item.shape+",type="+typehash[item.type]+",min_tol="+item.min_tol+
			",max_tol="+item.max_tol+",bit=,finish_size="+item.finish_size+
			",drill_size="+item.drill_size+",combined=yes,orig_size=0")
		} else if (item.shape == "slot") {
            if (item.slot_len != "" && Number(item.slot_len) > 0) {
                GEN.COM("tools_tab_add,num="+key+",shape=slot,type="+typehash[item.type]+",min_tol="+item.min_tol+",max_tol="+item.max_tol+",finish_size="+item.finish_size+
                ",bit=,drill_size="+item.drill_size+",slot_len="+item.slot_len)
            } else {
                GEN.COM("tools_tab_add,num="+key+",shape=slot,type="+typehash[item.type]+",min_tol="+item.min_tol+",max_tol="+item.max_tol+",finish_size="+item.finish_size+
                ",bit=,drill_size="+item.drill_size)
            }
		}
	
	})
	GEN.COM("tools_set,layer="+layer+",slots=by_length")

	GEN.units({type:units})
}


function foo (data) {
	if (Number(data) % 10 == 0) {
			return Number(data) + 3
	} else {
			return Number(data)
	}
}
